import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Skeleton, Toast } from "antd-mobile";
import { informationService, collectionService, handleApiResponse, handleApiError } from "../../../utils/api";
import backImg from "../../../assets/icon/common_icon_back_black_n.png";
import indetailImg from "../../../assets/icon/common_nav_message_black_n.png";
import DOMPurify from "dompurify";
import { format } from "date-fns";
import common_button_collection_large_n from '../../../assets/icon/common_button_collection_large_n.png'
import common_button_collection_large_s from '../../../assets/icon/common_button_collection_large_s.png'
import "./index.css";

const Index: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [informationDetail, setInformationDetail] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [isCollected, setIsCollected] = useState<boolean>(false);
  const [isCollecting, setIsCollecting] = useState<boolean>(false);

  useEffect(() => {
    if (!id) return;

    const fetchInformationDetail = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await informationService.getInformationDetail(Number(id));
        const data = handleApiResponse(response) as any;
        
        // 格式化发布时间
        if (data.releaseTime && typeof data.releaseTime === 'string') {
          data.releaseTime = format(data.releaseTime, "yyyy-MM-dd HH:mm:ss");
        }
        
        setInformationDetail(data);
        setLoading(false);
      } catch (err) {
        const errorMsg = handleApiError(err);
        setError(errorMsg);
        setLoading(false);
        console.error('获取资讯详情失败:', errorMsg);
      }
    };

    fetchInformationDetail();
  }, [id]);

  // 处理收藏/取消收藏
  const handleCollection = async () => {
    // 检查是否登录
    const userInfo = localStorage.getItem('userInfo');
    if (!userInfo) {
      Toast.show({
        content: '请先登录',
        duration: 2000,
      });
      navigate('/login');
      return;
    }

    if (!id) return;

    setIsCollecting(true);
    try {
      if (isCollected) {
        // 取消收藏资讯
        await collectionService.cancelInfoCollection(Number(id));
        setIsCollected(false);
        Toast.show({
          content: '取消收藏成功',
          duration: 2000,
        });
      } else {
        // 收藏资讯
        await collectionService.addInfoCollection(Number(id));
        setIsCollected(true);
        Toast.show({
          content: '收藏成功',
          duration: 2000,
        });
      }
    } catch (error) {
      console.error('收藏操作失败:', error);
      Toast.show({
        content: '操作失败，请稍后重试',
        duration: 2000,
      });
    } finally {
      setIsCollecting(false);
    }
  };
  

  return (
    <div className="imdetail_box">
      <div className="imdetail_top_box">
        <img src={backImg} alt="" onClick={() => navigate(-1)} />
        <span>资讯详情</span>
        <img src={indetailImg} alt="" />
      </div>
      {!loading && informationDetail ? (
        <div className="imdetail_content_box">
          <div className="imdetail_title">{informationDetail.title}</div>
          <div className="imdetail_info">
            <span className="imdetail_info_name">
              {informationDetail.source}
            </span>
            <span className="imdetail_info_time">
              {informationDetail.releaseTime}
            </span>
          </div>
          <div className="imdetail_content">
            <div
              dangerouslySetInnerHTML={{
                __html: DOMPurify.sanitize(informationDetail.content),
              }}
            />
          </div>
        </div>
      ) : error ? (
        <div style={{ textAlign: 'center', padding: '20px', color: 'red' }}>
          {error}
        </div>
      ) : (
        <div className="Skeleton">
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={8} animated />
        </div>
      )}
      
      {/* 固定在右下角的收藏按钮 */}
      {!loading && informationDetail && (
        <div className="collection-button" onClick={handleCollection}>
          <img 
            src={isCollected ? common_button_collection_large_s : common_button_collection_large_n} 
            alt={isCollected ? "已收藏" : "收藏"} 
            className={isCollecting ? "collecting" : ""}
          />
        </div>
      )}
    </div>
  );
};

export default Index;
